﻿using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Linq;

using Com.Ompchina.Lib.Net;
using Util.Configuration;
namespace Util.Map.Baidu
{
    /// <summary>
    /// 地图操作，百度地图，地址转换为坐标
    /// </summary>
    public class AddressConvertLocation
    {
        /// <summary>
        /// 获取坐标地址的地址
        /// </summary>
        /// <param name="address"></param>
        /// <returns></returns>
        public static string[] ConvertLocation(string address) 
        {
            return AddressConvertLocation.ConvertLocation(address, WebConfiguration.BaiduMapKey);
        }

        /// <summary>
        /// 获取坐标地址的地址
        /// </summary>
        /// <param name="address"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string[] ConvertLocation(string address, string key) 
        {
            Dictionary<string, string> para = new Dictionary<string, string> { 
                {"address",address}, {"output","xml"}, {"key",key}
            };
            string resultXML = new RequestURI().RequestMethod("http://api.map.baidu.com/geocoder", RequestURIMethod.GET, para, CharacterSet.UTF8, CharacterSet.UTF8);
            if (!string.IsNullOrEmpty(resultXML)) 
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(resultXML);
                XmlNode xn = doc.SelectSingleNode("/GeocoderSearchResponse/result/precise");
                if (xn.InnerText.Equals("1"))
                {
                    return new string[] { 
                        doc.SelectSingleNode("/GeocoderSearchResponse/result/location/lng").InnerText
                        , doc.SelectSingleNode("/GeocoderSearchResponse/result/location/lat").InnerText
                    };
                }
                else
                    return new string[2];
            }
            return new string[2];
        }
    }
}
